﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;

namespace VG.EAP.Common
{
    /// <summary>
    /// 分页控件 Smith
    /// </summary>
    [DefaultProperty("PageSize"), ToolboxData("<{0}:PagerToolBar runat=\"server\"></{0}:PagerToolBar>")]
    public class PagerToolBar : System.Web.UI.WebControls.WebControl, INamingContainer
    {
        public System.EventHandler OnPagerToolBarClick;

        #region PageIndex PageSize ... Property
        public int PageIndex
        {
            get
            {
                if (this.ViewState["$PageIndex"] == null)
                {
                    return 1;
                }
                return (int)this.ViewState["$PageIndex"];
            }
            set
            {
                if (value <= 1)
                {
                    this.ViewState["$PageIndex"] = 1;
                }
                else
                {
                    this.ViewState["$PageIndex"] = value;
                }

                this.txtPageIndex.Text = PageIndex.ToString();
            }
        }


        public int PageSize
        {
            get
            {
                if (this.ViewState["$PageSize"] == null)
                {
                    this.ViewState["$PageSize"] = 20;
                }
                else
                {
                    for (int i = 0; i < this.ddlPageSize.Items.Count; i++)
                    {
                        if (this.ddlPageSize.Items[i].Value == this.ViewState["$PageSize"].ToString())
                        {
                            this.ddlPageSize.SelectedValue = this.ViewState["$PageSize"].ToString();
                            break;
                        }
                        else
                        {
                            if (i == 0 && int.Parse(ddlPageSize.Items[i].Value) > int.Parse(this.ViewState["$PageSize"].ToString()))
                            {
                                this.ddlPageSize.Items.Insert(0, new ListItem(this.ViewState["$PageSize"].ToString(), this.ViewState["$PageSize"].ToString()));
                                this.ddlPageSize.SelectedValue = this.ViewState["$PageSize"].ToString();
                                break;
                            }
                            else if ((int.Parse(ddlPageSize.Items[i].Value) < int.Parse(this.ViewState["$PageSize"].ToString()) && int.Parse(ddlPageSize.Items[i + 1].Value) > int.Parse(this.ViewState["$PageSize"].ToString())) || i == this.ddlPageSize.Items.Count + 1)
                            {
                                this.ddlPageSize.Items.Insert(i + 1, new ListItem(this.ViewState["$PageSize"].ToString(), this.ViewState["$PageSize"].ToString()));
                                this.ddlPageSize.SelectedValue = this.ViewState["$PageSize"].ToString();
                                break;
                            }
                        }
                    }
                }
                return (int)this.ViewState["$PageSize"];
            }
            set
            {
                if (value <= 1)
                {
                    this.ViewState["$PageSize"] = 1;
                }
                else
                {
                    this.ViewState["$PageSize"] = value;
                }
            }
        }

        public int PageCount
        {
            get
            {
                if (this.RecordCount <= 0)
                {
                    return 1;
                }

                if (this.RecordCount % this.PageSize != 0)
                {
                    return this.RecordCount / this.PageSize + 1;
                }
                else
                {
                    return this.RecordCount / this.PageSize;
                }
            }
        }

        public int RecordCount
        {
            get
            {
                if (this.ViewState["$RecordCount"] == null)
                {
                    this.ViewState["$RecordCount"] = 0;
                }
                return (int)this.ViewState["$RecordCount"];
            }
            set
            {
                if (value <= 1)
                {
                    this.ViewState["$RecordCount"] = 1;

                    if (value == 0)
                    {
                        this.ViewState["$RecordCount"] = 0;
                    }
                }
                else
                {
                    this.ViewState["$RecordCount"] = value;
                }
            }
        }


        private string VirtualHostRoot
        {
            get
            {
                return "~/";
            }
        }
        #endregion

        #region 基本控件定义
        protected DropDownList ddlPageSize = new DropDownList();
        protected ImageButton linkPagePrev = new ImageButton();
        protected ImageButton linkPageNext = new ImageButton();
        protected ImageButton linkPageFirst = new ImageButton();
        protected ImageButton linkPageLast = new ImageButton();
        protected ImageButton linkGo = new ImageButton();
        protected TextBox txtPageIndex = new TextBox();
        protected LiteralControl ltPageIndex = new LiteralControl();
        protected LiteralControl ltPageCount = new LiteralControl();
        protected LiteralControl ltRecordCount = new LiteralControl();
        private System.ComponentModel.IContainer components;

        private Control _grid = null;
        public Control Grid
        {
            set
            {
                _grid = value;
            }
            get
            {
                return _grid;
            }
        }

        #endregion

        #region Init Load Create Control Events Render
        /// <summary>
        /// Step 1： Init
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();

            base.OnInit(e);
        }

        /// <summary>
        /// Step 2: InitializeComponent
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();

            this.linkGo.ID = "lnkGo";

            this.linkPageFirst.ImageUrl = string.Format(@"{0}_imgs/PageFirst.gif", this.VirtualHostRoot);
            this.linkPagePrev.ImageUrl = string.Format(@"{0}_imgs/PagePrev.gif", this.VirtualHostRoot);
            this.linkPageNext.ImageUrl = string.Format(@"{0}_imgs/PageNext.gif", this.VirtualHostRoot);
            this.linkPageLast.ImageUrl = string.Format(@"{0}_imgs/PageLast.gif", this.VirtualHostRoot);
            this.linkGo.ImageUrl = string.Format(@"{0}_imgs/Go.gif", this.VirtualHostRoot);

            this.linkPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.linkPageFirst_Click);
            this.linkPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.linkPagePrev_Click);
            this.linkPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.linkPageNext_Click);
            this.linkPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.linkPageLast_Click);
            this.linkGo.Click += new ImageClickEventHandler(linkGo_Click);

            this.linkPageFirst.Style.Add("Cursor", "Hand");
            this.linkPagePrev.Style.Add("Cursor", "Hand");
            this.linkPageNext.Style.Add("Cursor", "Hand");
            this.linkPageLast.Style.Add("Cursor", "Hand");
            this.linkGo.Style.Add("Cursor", "Hand");

            this.Load += new EventHandler(PagerToolBar_Load);
            this.ddlPageSize.SelectedIndexChanged += new EventHandler(ddlPageSize_SelectedIndexChanged);
        }

        /// <summary>
        /// Step 3: Page Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void PagerToolBar_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.PageIndex = 1;
            }
        }

        /// <summary>
        /// Step4 : Create Controls
        /// </summary>
        protected override void CreateChildControls()
        {
            #region 初始化 PageSize的 DropdownList
            this.ddlPageSize.Items.Add(new ListItem("10", "10"));
            this.ddlPageSize.Items.Add(new ListItem("20", "20"));
            this.ddlPageSize.Items.Add(new ListItem("50", "50"));
            this.ddlPageSize.Items.Add(new ListItem("100", "100"));
            this.ddlPageSize.AutoPostBack = true;
            this.ddlPageSize.SelectedIndex = 1;
            #endregion

            this.Controls.Add(new LiteralControl("<TABLE width='100%'>"));
            this.Controls.Add(new LiteralControl("<TR>"));

            this.Controls.Add(new LiteralControl("<TD>"));

            #region 每页行数选择
            this.Controls.Add(new LiteralControl("<TABLE align='left'>"));
            this.Controls.Add(new LiteralControl("<TR>"));

            this.Controls.Add(new LiteralControl("<TD>"));
            this.Controls.Add(new LiteralControl(" Page Size： "));
            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("<TD>"));
            this.Controls.Add(this.ddlPageSize);
            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("</TR>"));
            this.Controls.Add(new LiteralControl("</TABLE>"));
            #endregion

            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("<TD>"));

            #region 分页控件部分
            this.Controls.Add(new LiteralControl("<TABLE align='right'>"));
            this.Controls.Add(new LiteralControl("<TR>"));

            #region 显示第几页和总页数
            this.Controls.Add(new LiteralControl("<TD width='80px'>"));
            this.Controls.Add(ltPageIndex);
            this.Controls.Add(new LiteralControl(" / "));
            this.Controls.Add(ltPageCount);
            this.Controls.Add(new LiteralControl("</TD>"));
            #endregion

            #region 显示总行数
            this.Controls.Add(new LiteralControl("<TD width='120px'>"));
            this.Controls.Add(new LiteralControl(" Total: "));
            this.Controls.Add(ltRecordCount);
            this.Controls.Add(new LiteralControl(" "));
            this.Controls.Add(new LiteralControl("</TD>"));
            #endregion

            #region 上页、下页、第一页、最后一页按钮
            this.Controls.Add(new LiteralControl("<TD width='22px'>"));
            this.Controls.Add(linkPageFirst);
            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("<TD width='20px'>"));
            this.Controls.Add(linkPagePrev);
            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("<TD width='20px'>"));
            this.Controls.Add(linkPageNext);
            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("<TD width='22px'>"));
            this.Controls.Add(linkPageLast);
            this.Controls.Add(new LiteralControl("</TD>"));
            #endregion

            #region 转到按钮
            this.Controls.Add(new LiteralControl("<TD>GO:</TD>"));

            this.Controls.Add(new LiteralControl("<TD>"));
            this.txtPageIndex.Width = new Unit("48px");
            this.Controls.Add(this.txtPageIndex);
            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("<TD>"));
            this.Controls.Add(this.linkGo);
            this.Controls.Add(new LiteralControl("</TD>"));
            #endregion

            this.Controls.Add(new LiteralControl("</TR>"));
            this.Controls.Add(new LiteralControl("</TABLE>"));
            #endregion

            this.Controls.Add(new LiteralControl("</TD>"));

            this.Controls.Add(new LiteralControl("</TR>"));
            this.Controls.Add(new LiteralControl("</TABLE>"));


        }

        //Step 5: 执行控件的事件
        #region Events
        private void linkPageNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (this.OnPagerToolBarClick != null)
            {
                this.PageIndex += 1;
                OnPagerToolBarClick(this, new PagerToolBarEventArgs(ToolBarEnum.PageNext));
            }
        }

        private void linkPagePrev_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (this.OnPagerToolBarClick != null)
            {
                this.PageIndex -= 1;
                OnPagerToolBarClick(this, new PagerToolBarEventArgs(ToolBarEnum.PagePrev));
            }
        }

        private void linkPageFirst_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (this.OnPagerToolBarClick != null)
            {
                this.PageIndex = 1;
                OnPagerToolBarClick(this, new PagerToolBarEventArgs(ToolBarEnum.PagePrev));
            }
        }

        private void linkPageLast_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (this.OnPagerToolBarClick != null)
            {
                this.PageIndex = this.PageCount;
                OnPagerToolBarClick(this, new PagerToolBarEventArgs(ToolBarEnum.PagePrev));
            }
        }

        private void linkGo_Click(object sender, ImageClickEventArgs e)
        {
            if (this.OnPagerToolBarClick != null)
            {
                int pageIndex = 0;
                try
                {
                    pageIndex = System.Int32.Parse(this.txtPageIndex.Text);
                }
                catch
                {
                    pageIndex = this.PageIndex;
                    this.txtPageIndex.Text = this.PageIndex.ToString();

                    return;
                }

                if (this.PageIndex == pageIndex)
                {
                    return;
                }

                if (pageIndex > PageCount)
                    pageIndex = PageCount;

                this.PageIndex = pageIndex;

                OnPagerToolBarClick(this, new PagerToolBarEventArgs(ToolBarEnum.GotoPage));
            }
        }

        void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            int size = 10;
            int.TryParse(this.ddlPageSize.SelectedValue, out size);
            this.PageSize = size;

            OnPagerToolBarClick(this, new PagerToolBarEventArgs(ToolBarEnum.GotoPage));

        }
        #endregion

        //Step 6：Render
        protected override void OnPreRender(EventArgs e)
        {
            this.txtPageIndex.Text = this.PageIndex.ToString();
            this.ltPageIndex.Text = this.PageIndex.ToString();
            this.ltPageCount.Text = this.PageCount.ToString();
            this.ltRecordCount.Text = this.RecordCount.ToString();

            this.SetStatus();
        }
        #endregion

        #region SetStatus Pager Button Status Function
        private void SetStatus()
        {
            if (PageIndex <= 1)
            {
                this.linkPageFirst.Enabled = false;
                this.linkPagePrev.Enabled = false;
                //this.linkPageFirst.ImageUrl = string.Format("../_imgs/page_FL0.gif", this.VirtualHostRoot);
                //this.linkPagePrev.ImageUrl = string.Format("../_imgs/page_L0.gif", this.VirtualHostRoot);

            }
            else
            {
                this.linkPageFirst.Enabled = true;
                this.linkPagePrev.Enabled = true;
                //this.linkPageFirst.ImageUrl = string.Format("../_imgs/page_FL1.gif", this.VirtualHostRoot);
                //this.linkPagePrev.ImageUrl = string.Format("../_imgs/page_L1.gif", this.VirtualHostRoot);
            }
            if (RecordCount <= PageSize * PageIndex)
            {
                this.linkPageNext.Enabled = false;
                this.linkPageLast.Enabled = false;
            }
            else
            {
                this.linkPageNext.Enabled = true;
                this.linkPageLast.Enabled = true;
            }
        }
        #endregion

        #region DataBind
        public void DataBind(System.Data.DataTable dt)
        {
            if (this.Grid != null)
            {
                if (_grid is Repeater)
                {

                    (this._grid as Repeater).DataSource = dt;
                }
                if (_grid is GridView)
                {

                    (this._grid as GridView).DataSource = dt;
                }
                this._grid.DataBind();
            }
        }

        public void DataBindList<T>(IList<T> list)
        {
            if (this.Grid != null)
            {
                if (_grid is Repeater)
                {

                    (this._grid as Repeater).DataSource = list;
                }
                if (_grid is GridView)
                {

                    (this._grid as GridView).DataSource = list;
                }
                this._grid.DataBind();
            }
        }

        public void DataBind<T>(IList<T> list) where T : BaseEntity, new()
        {
            if (this.Grid != null)
            {
                if (_grid is Repeater)
                {

                    (this._grid as Repeater).DataSource = list;
                }
                if (_grid is GridView)
                {

                    (this._grid as GridView).DataSource = list;
                }
                this._grid.DataBind();
            }
        }
        #endregion
    }


    public enum ToolBarEnum
    {
        PageNext = 0,
        PagePrev = 1,
        GotoPage = 2
    }

    public class PagerToolBarEventArgs : System.EventArgs
    {
        public PagerToolBarEventArgs(ToolBarEnum toolBarEnum)
        {
            this.ToolBarEnum = toolBarEnum;
        }
        public ToolBarEnum ToolBarEnum;
    }
}


